<template>
  <div>
    <vxe-grid
      ref="xGrid"
      v-bind="grid"
      @cell-menu="
        ({ row }) => {
          this.$refs.xGrid.setCurrentRow(row);
        }
      "
      @menu-click="contextMenuClickEvent"
    >
      <template #toolbar_buttons>
        <eip-toolbar
          @del="del"
          @update="update"
          @add="add"
          @onload="toolbarOnload"
          @downTemplate="downTemplate"
          @dataImport="dataImport"
          @mapShow="mapShow"
          @treeShow="treeShow"
        ></eip-toolbar>
        <a-space class="margin-left-sm">
          <a-button
            icon="fullscreen"
            type="link"
            @click="$refs.xGrid.setAllTreeExpand(true)"
            >展开所有</a-button
          >
          <a-button
            icon="fullscreen-exit"
            type="link"
            @click="$refs.xGrid.clearTreeExpand()"
            >关闭所有</a-button
          >
        </a-space>
      </template>
      <template #toolbar_tools> </template>
      <template #loading>
        <a-spin></a-spin>
      </template>
      <template #empty>
        <eip-empty />
      </template>
      <template #radio="{ row, checked }">
        <span @click.stop="$refs.xGrid.toggleCheckboxRow(row)">
          <a-radio :checked="checked"> </a-radio>
        </span>
      </template>
      <template #isFreeze="{ row }">
        <a-switch :checked="row.isFreeze" @change="isFreezeChange(row)" />
      </template>
      <template #latlng="{ row }">
        <a-tag color="blue" v-if="row.longitude">
          经度：{{ row.longitude }}
        </a-tag>
        <a-tag color="purple" v-if="row.latitude">
          纬度：{{ row.latitude }}
        </a-tag>
      </template>
      <template #nature="{ row }">
        {{
          eipOrganizationNatures.filter((f) => f.value == row.nature).length > 0
            ? eipOrganizationNatures.filter((f) => f.value == row.nature)[0]
                .name
            : ""
        }}
      </template>
      <template #operate="{ row }">
        <a-tooltip
          @click="tableUpdateRow(row)"
          title="编辑"
          v-if="visible.update"
        >
          <label class="text-eip eip-cursor-pointer">编辑</label>
        </a-tooltip>
        <a-divider type="vertical" v-if="visible.update" />
        <a-tooltip title="删除" v-if="visible.del" @click="tableDelRow(row)">
          <label class="text-red eip-cursor-pointer">删除</label>
        </a-tooltip>
      </template>
    </vxe-grid>

    <edit
      ref="edit"
      v-if="edit.visible"
      :visible.sync="edit.visible"
      :title="edit.title"
      :organizationId="edit.organizationId"
      :parentId="edit.parentId"
      :parentName="edit.parentName"
      @save="operateStatus"
    >
    </edit>

    <maplist
      ref="map"
      v-if="map.visible"
      :visible.sync="map.visible"
      :title="map.title"
    >
    </maplist>

    <tree
      ref="tree"
      v-if="tree.visible"
      :visible.sync="tree.visible"
      :title="tree.title"
    >
    </tree>
  </div>
</template>

<script>
import {
  query,
  del,
  isFreeze,
  downImportTemplate,
  systemOrganizationImport,
} from "@/services/system/organization/list";
import edit from "./edit";
import maplist from "./maplist";
import tree from "./tree";

import { selectTableRowRadio, deleteConfirm } from "@/utils/util";
export default {
  components: {
    edit,
    maplist,
    tree,
  },
  data() {
    return {
      map: {
        visible: false,
        title: "",
      },
      tree: {
        visible: false,
        title: "",
      },
      organization: {
        data: [],
        right: [],
      },

      grid: {
        id: "organization",
        loading: true,
        height: this.eipTableHeight(),
        customConfig: {
          mode: "popup",
        },
        treeConfig: {
          transform: true,
          rowField: "organizationId",
          parentField: "parentId",
          reserve: true,
          trigger: "default",
        },
        rowConfig: {
          keyField: "organizationId",
        },

        menuConfig: {
          header: {
            options: [
              [
                {
                  code: "exportAll",
                  name: "导出所有.csv",
                  prefixIcon: "vxe-icon-download",
                  visible: true,
                  disabled: false,
                },
              ],
            ],
          },
          body: {
            options: [
              [
                {
                  code: "1",
                  name: "新增",
                  prefixIcon: "vxe-icon-add",
                  visible: true,
                  disabled: false,
                },
                {
                  code: "2",
                  name: "编辑",
                  prefixIcon: "vxe-icon-signature",
                  visible: true,
                  disabled: false,
                },
                {
                  code: "3",
                  name: "删除",
                  prefixIcon: "vxe-icon-delete",
                  visible: true,
                  disabled: false,
                },
              ],
              [
                {
                  code: "print",
                  name: "打印",
                  prefixIcon: "vxe-icon-print",
                  visible: true,
                  disabled: false,
                },
                {
                  code: "export",
                  name: "导出.csv",
                  prefixIcon: "vxe-icon-download",
                  visible: true,
                  disabled: false,
                },
              ],
            ],
          },
          footer: {
            options: [
              [
                {
                  code: "exportAll",
                  name: "导出所有.csv",
                  prefixIcon: "vxe-icon-download",
                  visible: true,
                  disabled: false,
                },
              ],
            ],
          },
        },
        filterConfig: {
          remote: true,
        },
        sortConfig: {
          trigger: "cell",
          defaultSort: { field: "orderNo", order: "desc" },
          orders: ["desc", "asc", null],
          remote: true,
          multiple: true,
          chronological: true,
        },
        printConfig: {},
        exportConfig: {},
        toolbarConfig: {
          slots: {
            buttons: "toolbar_buttons",
            tools: "toolbar_tools",
          },
        },
        proxyConfig: {
          seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
          ajax: {
            query: ({ page, sorts, filters, form }) => {
              return new Promise((resolve) => {
                query({ filters: this.eipTableFilter(filters) }).then(
                  (result) => {
                    if (result.code == this.eipResultCode.success) {
                      resolve(result.data);
                    }
                    this.grid.loading = false;
                  }
                );
              });
            },
          },
        },
        columns: [
          {
            type: "radio",
            width: 50,
            slots: {
              radio: "radio",
            },
            align: "center",
            fixed: "left",
          },
          { type: "seq", width: 60, fixed: "left" },
          {
            field: "name",
            treeNode: true,
            title: "全称",
            width: 220,
            fixed: "left",
            showOverflow: "ellipsis",
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "shortName",
            title: "简称",
            width: 220,
            showOverflow: "ellipsis",
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "longitude",
            treeNode: true,
            title: "经纬度",
            width: 120,
            showOverflow: "ellipsis",
            slots: {
              default: "latlng",
            },
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "isShowMenu",
            title: "类型",
            width: 120,
            showOverflow: true,
            slots: {
              default: "nature",
            },
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "switch",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [
                    {
                      value: 0,
                      label: "否",
                      checked: false,
                      color: "red",
                    },
                    {
                      value: 1,
                      label: "是",
                      checked: false,
                      color: "#1890ff",
                    },
                  ],
                },
              },
            ],
          },

          {
            field: "mainSupervisor",
            title: "主负责人",
            width: 150,
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "mainSupervisorContact",
            title: "主负责人联系方式",
            width: 200,
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "isFreeze",
            title: "禁用",
            width: 120,
            showOverflow: true,
            slots: {
              default: "isFreeze",
            },
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "switch",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [
                    {
                      value: 1,
                      label: "已禁用",
                      checked: false,
                      color: "red",
                    },
                    {
                      value: 0,
                      label: "未禁用",
                      checked: false,
                      color: "#1890ff",
                    },
                  ],
                },
              },
            ],
          },

          {
            field: "remark",
            title: "备注",
            width: 150,
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "orderNo",
            title: "排序号",
            width: 120,
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "number",
                  op: "cn",
                  write: null,
                  min: null,
                  max: null,
                },
              },
            ],
          },
          {
            field: "createUserName",
            title: "创建人",
            width: 150,
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "createTime",
            title: "创建时间",
            width: 150,
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "datetime",
                  op: "cn",
                  write: null,
                  min: null,
                  max: null,
                },
              },
            ],
          },
          {
            field: "updateUserName",
            title: "修改人",
            width: 150,
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "updateTime",
            title: "修改时间",
            width: 150,
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "datetime",
                  op: "cn",
                  write: null,
                  min: null,
                  max: null,
                },
              },
            ],
          },
          {
            title: "操作",
            width: 100,
            align: "center",
            fixed: "right",
            slots: {
              default: "operate",
            },
          },
        ],
        data: [],

        extend: {
          id: null,
        },
      },

      edit: {
        visible: false,
        organizationId: "",
        parentId: "",
        parentName: null,
        title: "",
      },

      visible: {
        add: false,
        update: false,
        del: false,
      },
    };
  },

  created() {},

  methods: {
    /**
     * 组织树
     */
    treeShow() {
      let that = this;
      that.tree.visible = true;
    },
    /**
     * 区域地图
     */
    mapShow() {
      let that = this;
      that.map.visible = true;
    },

    /**
     * 右键点击
     * @param {*} param0
     */
    contextMenuClickEvent({ menu, row, column }) {
      switch (menu.code) {
        case "1":
          this.organizationAdd(row);
          break;
        case "2":
          this.organizationUpdate(row);
          break;
        case "3":
          this.organizationDel(row);
          break;
        default:
          break;
      }
    },

    /**
     *冻结
     */
    isFreezeChange(row) {
      if (this.visible.update) {
        let that = this;
        isFreeze({ id: row.organizationId }).then((result) => {
          that.$message.destroy();
          if (result.code == that.eipResultCode.success) {
            that.reload(false);
            that.$message.success(result.msg);
          } else {
            that.$message.error(result.msg);
          }
        });
      }
    },

    /**
     * 树删除
     */
    organizationDel(item) {
      let that = this;
      deleteConfirm(
        "组织架构【" + item.name + "】" + that.eipMsg.delete,
        function () {
          that.$loading.show({ text: that.eipMsg.delloading });
          del({ id: item.organizationId }).then((result) => {
            that.$loading.hide();
            if (result.code == that.eipResultCode.success) {
              that.reload(false);
              that.$message.success(result.msg);
            } else {
              that.$message.error(result.msg);
            }
          });
        },
        that
      );
    },

    /**
     * 树新增
     */
    organizationAdd(item) {
      this.edit.title = "新增组织架构";
      this.edit.parentId = item.organizationId;
      this.edit.parentName = item.name;
      this.edit.organizationId = null;
      this.edit.visible = true;
    },

    /**
     * 树更新
     */
    organizationUpdate(item) {
      this.edit.organizationId = item.organizationId;
      this.edit.parentId = "";
      this.edit.parentName = "";
      this.edit.title = "编辑组织架构-" + item.name;
      this.edit.visible = true;
    },
    /**
     * 树右键
     */
    right({ event, node }) {
      this.organization.right.visible = true;
      this.organization.right.item = {
        id: node._props.eventKey,
        title: node._props.title,
      };
    },

    /**
     * 树右键菜单隐藏
     */
    hideRight() {
      this.organization.right.visible = false;
      this.organization.right.item = null;
    },

    /**
     * 列表数据
     */
    tableInit() {
      this.$refs.xGrid.commitProxy("query");
    },

    /**
     * 权限按钮加载完毕
     */
    toolbarOnload(buttons) {
      let addButton = buttons.filter((f) => f.method == "add");
      this.visible.add = addButton.length > 0;

      let updateButton = buttons.filter((f) => f.method == "update");
      this.visible.update = updateButton.length > 0;

      let delButton = buttons.filter((f) => f.method == "del");
      this.visible.del = delButton.length > 0;

      var organizations = [];
      if (this.visible.add) {
        organizations.push({
          code: "1",
          prefixIcon: "vxe-icon-add",
          name: addButton[0].name,
        });
      }
      if (this.visible.update) {
        organizations.push({
          code: "2",
          prefixIcon: "vxe-icon-" + updateButton[0].icon,
          name: updateButton[0].name,
        });
      }
      if (this.visible.del) {
        organizations.push({
          code: "3",
          prefixIcon: "vxe-icon-" + delButton[0].icon,
          name: delButton[0].name,
        });
      }
      this.organization.right.push(organizations);
    },

    /**
     * 树更新
     */
    tableUpdateRow(row) {
      this.edit.title = "组织架构编辑-" + row.name;
      this.edit.parentId = "";
      this.edit.parentName = "";
      this.edit.organizationId = row.organizationId;
      this.edit.visible = true;
    },

    /**
     * 删除
     */
    tableDelRow(row) {
      let that = this;
      deleteConfirm(
        "组织架构【" + row.name + "】" + that.eipMsg.delete,
        function () {
          that.$loading.show({ text: that.eipMsg.delloading });
          del({ id: row.organizationId }).then((result) => {
            that.$loading.hide();
            if (result.code == that.eipResultCode.success) {
              that.reload(false);
              that.$message.success(result.msg);
            } else {
              that.$message.error(result.msg);
            }
          });
        },
        that
      );
    },

    /**
     * 新增
     */
    add() {
      this.edit.title = "新增组织架构";
      this.edit.parentId = undefined;
      this.edit.parentName = "";
      this.edit.organizationId = null;
      this.edit.visible = true;
    },

    /**
     * 修改
     */
    update() {
      let that = this;
      selectTableRowRadio(
        that.$refs.xGrid,
        function (row) {
          that.edit.parentId = "";
          that.edit.parentName = "";
          that.edit.organizationId = row.organizationId;
          that.edit.title = "编辑组织架构-" + row.name;
          that.edit.visible = true;
        },
        that
      );
    },

    /**
     * 删除
     */
    del() {
      let that = this;
      selectTableRowRadio(
        that.$refs.xGrid,
        function (row) {
          //提示是否删除
          deleteConfirm(
            that.eipMsg.delete,
            function () {
              that.$loading.show({ text: that.eipMsg.delloading });
              del({ id: row.organizationId }).then((result) => {
                that.$loading.hide();
                if (result.code == that.eipResultCode.success) {
                  that.reload(false);
                  that.$message.success(result.msg);
                } else {
                  that.$message.error(result.msg);
                }
              });
            },
            that
          );
        },
        that,
        false
      );
    },

    /**
     * 下载导入模版
     */
    downTemplate() {
      downImportTemplate();
    },

    /**
     *
     */
    dataImport(file) {
      let that = this;
      const formData = new FormData();
      formData.append("Files", file.file);
      that.$message.loading({
        content: "导入中...",
        duration: 0,
      });
      systemOrganizationImport(formData)
        .then((result) => {
          that.$message.destroy();
          if (result.code == that.eipResultCode.success) {
            that.$message.success(result.msg);
            that.reload();
          } else {
            var msg = [];
            try {
              var datas = JSON.parse(result.msg);
              datas.forEach((item) => {
                var m = "";
                m += "第" + item.RowIndex + "行，";
                for (let key in item.FieldErrors) {
                  m += item.FieldErrors[key] + ",";
                }
                msg.push(m);
              });
              that.upload.msg = msg.join("<br/>");
              that.upload.visible = true;
            } catch (error) {
              result.data.forEach((item) => {
                msg.push(item);
              });
              that.upload.msg = msg.join("<br/>");
              that.upload.visible = true;
            }
          }
        })
        .catch(() => {
          that.$message.error("上传出错");
        });
    },

    //提示状态信息
    operateStatus(result) {
      if (result.code === this.eipResultCode.success) {
        this.reload(false);
      }
    },

    /**
     * 重新加载
     */
    reload(reset) {
      if (reset) this.grid.extend.id = null;
      this.tableInit();
    },
  },
};
</script>
